package singletontest;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 静态内置类可以达到线程安全问题，但如果遇到序列化对象时，使用默认的方式运行得到的结果还是多例的。
 * <p>
 * 解决方法就是在反序列化中使用readResolve()方法：
 *
 * @author liuziyang
 * @create 2019-10-14 20:46
 */
public class SingletonTest8 implements Serializable {
    public static SingletonTest8 getInstance() {
        return SingletonTest8Handle.myObject;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        SingletonTest8 myObject = SingletonTest8.getInstance();
        FileOutputStream outputStream = new FileOutputStream(new File("myObject.txt"));
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(myObject);
        objectOutputStream.close();
        System.out.println(myObject.hashCode());

        FileInputStream inputStream = new FileInputStream(new File("myObject.txt"));
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        SingletonTest8 object = (SingletonTest8) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println(object.hashCode());
    }

    protected Object readResolve() {
        System.out.println("调用了readResolve方法");
        return SingletonTest8Handle.myObject;
    }

    //静态内部类
    public static class SingletonTest8Handle {
        private static final SingletonTest8 myObject = new SingletonTest8();
    }
}
